<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head th:replace="~{commons/adminCommon::adminHead('西安旅游电子票务后台')}">
        <title>西安旅游电子票务后台</title>
    </head>

    <body>
        <nav th:replace="~{commons/adminCommon::navHead}"></nav>

        <div class="container-fluid">
            <div class="row">
                <nav th:replace="~{commons/adminCommon::navbar(2)}"></nav>

                <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
                    <h2>景点管理</h2>
                    <hr>
                    <div class="row m-3">
                        <div class="col">
                            <a th:href="@{/admin/sites}" href="#"
                               class="btn btn-primary btn-sm mb-1">显示全部景点</a>
                            <div class="float-right">
                                <form th:action="@{/admin/site/search}" method="get"
                                      class="form-inline d-inline-block">
                                    <input type="text" class="form-control-sm" name="site" placeholder="请输入景点名称">
                                    <input type="submit" value="搜索景点" class="btn btn-info btn-sm mb-1"/>
                                </form>
                                <button data-toggle='modal' data-target='#add-site-modal'
                                        class="btn btn-info btn-sm mb-1 mx-3">
                                    添加景点
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>景点ID</th>
                                    <th>景点图片</th>
                                    <th>景点名称</th>
                                    <th>景点信息(简要)</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:each="site, stat : ${sitePage.records}">
                                    <td class="font-weight-bold" th:text="${stat.index + 1}">1</td>
                                    <td th:text="${site.siteId}">1</td>
                                    <td>
                                        <img th:src="@{${site.siteImg}}" src="../../static/img/img01.jpg" width="50px"
                                             height="50px">
                                    </td>
                                    <td th:text="${site.siteName}">华山</td>
                                    <td th:text="${#strings.abbreviate(site.siteInfo, 60)}" width="500px">华山</td>
                                    <td>
                                        <button class="btn btn-primary btn-sm" data-toggle='modal'
                                                data-target='#update-site-modal' th:data-siteid='${site.siteId}'>
                                            编辑
                                        </button>
                                        <button th:onclick="deleteSite([[${site.siteId}]])"
                                                class="btn btn-danger btn-sm">
                                            删除
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <h3 th:if="${sitePage.records.isEmpty()}" th:text="${searchMsg}"
                            class="text-danger text-center"></h3>
                        <nav aria-label="Page navigation example" class="mt-3 float-right"
                             th:object="${sitePage}" th:if="${sitePage.pages > 1}">
                            <ul class="pagination">
                                <li class="page-item" th:classappend="*{!hasPrevious()} ? 'disabled' : ''">
                                    <a class="page-link" th:href="@{/admin/sites(page=1)}" aria-label="Previous">首页</a>
                                </li>
                                <li class="page-item" th:classappend="*{hasPrevious()} ? '' : 'disabled'">
                                    <a class="page-link" th:if="*{(current - 1) > 0}"
                                       th:href="@{/admin/sites(page=*{current}-1)}"
                                       aria-label="Previous">上一页</a>
                                    <a class="page-link" th:if="*{(current - 1) <= 0}" th:href="@{/admin/sites(page=1)}"
                                       aria-label="Previous">上一页</a>
                                </li>
                                <li class="page-item" th:each="page : *{#numbers.sequence(1, pages)}"
                                    th:classappend="(${page}==*{current})?'active':''">
                                    <a class="page-link" th:href="@{/admin/sites(page=${page})}" th:text="${page}">1</a>
                                </li>
                                <li class="page-item" th:classappend="*{hasNext()} ? '' : 'disabled'">
                                    <a class="page-link" th:if="*{(current + 1) < pages}"
                                       th:href="@{/admin/sites(page=*{current}+1)}"
                                       aria-label="Previous">下一页</a>
                                    <a class="page-link" th:if="*{(current + 1) >= pages}"
                                       th:href="@{/admin/sites(page=*{pages})}"
                                       aria-label="Previous">下一页</a>
                                </li>
                                <li class="page-item" th:classappend="*{!hasNext()} ? 'disabled' : ''">
                                    <a class="page-link" th:href="@{/admin/sites(page=*{pages})}"
                                       aria-label="Previous">末页</a>
                                </li>
                            </ul>
                            <div class="text-primary text-center">
                                <span>第 <span th:text="*{current}">1</span> 页</span>
                                /
                                <span>共 <span th:text="*{pages}">10</span> 页</span>
                            </div>
                        </nav>
                    </div>
                </main>
            </div>
        </div>

        <!-- 添加景点信息模态框 -->
        <div id='add-site-modal' class='modal fade' tabindex='-1' role='dialog' aria-labelledby='my-modal-label'>
            <div class='modal-dialog modal-lg' role='document' aria-hidden='true'>
                <div class='modal-content'>
                    <div class='modal-header'>
                        <h3 id='my-modal-label1' class='modal-title text-primary'>添加景点信息</h3>
                    </div>
                    <div class='modal-body'>
                        <div class="form-group row">
                            <label for="siteName" class="col-form-label col-sm-2">景点名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="siteName" name="siteName"
                                       placeholder="请输入景点名称">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="ticketPrice" class="col-form-label col-sm-2">门票定价</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="ticketPrice" name="ticketPrice"
                                       value="100">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="siteInfo" class="col-form-label col-sm-2">景点描述</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" id="siteInfo" name="siteInfo"
                                          placeholder="请输入景点描述" style="height: 150px"></textarea>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-form-label col-sm-2">景点图片</label>
                            <div class="col-sm-10">
                                <input id="fileSelector" type="file" style="display: none" onchange="selectFile(this)">
                                <div class="thumb-box">
                                    <img class="img-thumbnail thumb" th:src="@{/img/imageup.png}"
                                         src="../../static/img/imageup.png" alt="thumb" onclick="thumbClick(this)">
                                    <i class="fas fa-window-close delete" onclick="thumbDelete(this)"></i>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div class='modal-footer'>
                        <button id="cancelModelBtn" type='button' class='btn btn-danger' data-dismiss='modal'>
                            取消
                        </button>
                        <button onclick="addSite()" id='addSiteBtn' type='button' class='btn btn-primary'>
                            添加
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 修改景点信息模态框 -->
        <div id='update-site-modal' class='modal fade' tabindex='-1' role='dialog' aria-labelledby='my-modal-label'>
            <div class='modal-dialog modal-lg' role='document' aria-hidden='true'>
                <div class='modal-content'>
                    <div class='modal-header'>
                        <h3 id='my-modal-label2' class='modal-title text-primary'>修改景点信息</h3>
                    </div>
                    <div class='modal-body'>
                        <div class="form-group row">
                            <label for="siteName2" class="col-form-label col-sm-2">景点名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="siteName2" name="siteName"
                                       placeholder="请输入景点名称">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="ticketPrice2" class="col-form-label col-sm-2">门票定价</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="ticketPrice2" name="ticketPrice"
                                       value="100">
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="siteInfo2" class="col-form-label col-sm-2">景点描述</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" id="siteInfo2" name="siteInfo"
                                          placeholder="请输入景点描述" style="height: 150px"></textarea>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label class="col-form-label col-sm-2">景点图片</label>
                            <div class="col-sm-10">
                                <input id="fileSelector2" type="file" style="display: none" onchange="selectFile(this)">
                                <div class="thumb-box">
                                    <img id="thumbImg" class="img-thumbnail thumb" th:src="@{/img/imageup.png}"
                                         src="../../static/img/imageup.png" alt="thumb" onclick="thumbClick(this)">
                                    <i class="fas fa-window-close delete" onclick="thumbDelete(this)"></i>
                                </div>
                                <br>
                            </div>
                        </div>
                    </div>
                    <div class='modal-footer'>
                        <button type='button' class='btn btn-danger' data-dismiss='modal'>
                            取消
                        </button>
                        <button id='updateSiteBtn' type='button' class='btn btn-primary'>
                            修改
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <th:block th:replace="~{commons/adminCommon::commonJs}"/>
        <script th:inline="javascript">
            // 删除景点
            function deleteSite(siteId) {
                bootstrapQ.confirm({title: "警告", msg: '此操作将永久删除此订单，确认删除?'},
                    function () {
                        let req = {};
                        req.siteId = siteId;
                        $.ajax({
                            url: /*[[@{/admin/site/deleteSite.do}]]*/'',
                            method: 'POST',
                            dataType: 'json',
                            data: JSON.stringify(req),
                            contentType: 'application/json;charset=utf-8',
                            processData: false,
                            success: function (resp) {
                                if (resp.success) {
                                    alert(resp.message);
                                    location.reload();
                                } else {
                                    bootstrapQ.msg({msg: resp.message, type: 'warning', time: 3000});
                                }
                            },
                            error: function (error) {
                                bootstrapQ.msg({msg: "网络异常 => " + error, type: 'danger', time: 3000});
                            }
                        })
                    }
                );
            }

            // 填充原来的数据
            $('#update-site-modal').on('show.bs.modal', function (event) {
                let button = $(event.relatedTarget)
                let siteId = button.data('siteid')
                let modal = $(this);
                modal.find('.modal-title').text('修改景点信息 ID => ' + siteId);
                document.getElementById('updateSiteBtn').onclick = function () {
                    updateSite(siteId);
                };

                // ajax
                let req = {};
                req.siteId = siteId;
                $.ajax({
                    url: /*[[@{/admin/site/findSiteById.do}]]*/'',
                    method: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(req),
                    contentType: 'application/json;charset=utf-8',
                    processData: false,
                    success: function (resp) {
                        if (resp.success) {
                            let site = resp.data.siteScenic;
                            let ticket = resp.data.siteTicket;
                            modal.find('.modal-body #siteName2').val(site.siteName);
                            modal.find('.modal-body #ticketPrice2').val(ticket.ticketPrice);
                            modal.find('.modal-body #siteInfo2').val(site.siteInfo);
                            $('.modal-body #thumbImg').attr("src", site.siteImg);
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 3000});
                        }
                    },
                    error: function (error) {
                        bootstrapQ.msg({msg: "网络异常 => " + error, type: 'danger', time: 3000});
                    }
                })
            })

            // 修改景点
            function updateSite(siteId) {
                let req = {};
                // 景点信息
                let site = {};
                site.siteId = siteId;
                site.siteName = $('#siteName2').val().trim();
                site.siteInfo = $('#siteInfo2').val().trim();
                site.siteImg = $('#thumbImg')[0].src.trim();
                req.site = site;

                // 对应的票信息
                let siteTicket = {};
                siteTicket.ticketPrice = $('#ticketPrice2').val().trim();
                req.siteTicket = siteTicket;

                $.ajax({
                    url: /*[[@{/admin/site/updateSite.do}]]*/'',
                    method: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(req),
                    contentType: 'application/json;charset=utf-8',
                    processData: false,
                    success: function (resp) {
                        if (resp.success) {
                            bootstrapQ.alert({msg: resp.message}, function () {
                                location.reload();
                            })
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 3000});
                        }
                    },
                    error: function (error) {
                        bootstrapQ.msg({msg: "网络异常 => " + error, type: 'danger', time: 3000});
                    }
                })
            }

            // 保存景点
            function addSite() {
                let req = {};
                // 景点信息
                let site = {};
                site.siteName = $('#siteName').val().trim();
                site.siteInfo = $('#siteInfo').val().trim();
                let siteImg = '';
                let thumb = $('.thumb');
                if (thumb[0].data != null) {
                    siteImg = thumb[0].data.url;
                }
                site.siteImg = siteImg;
                req.site = site;

                // 对应的票信息
                let siteTicket = {};
                siteTicket.ticketPrice = $('#ticketPrice').val().trim();
                req.siteTicket = siteTicket;

                if (req.site.siteName === '' || req.site.siteInfo === '' || req.site.siteImg === '') {
                    bootstrapQ.msg({msg: '请输入景点信息', type: 'warning', time: 3000});
                    return;
                }

                if (req.siteTicket.ticketPrice === 0 || req.siteTicket.ticketPrice === '') {
                    bootstrapQ.msg({msg: '请输入门票定价', type: 'warning', time: 3000});
                    return;
                }

                $.ajax({
                    url: /*[[@{/admin/site/addSite.do}]]*/'',
                    method: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(req),
                    contentType: 'application/json;charset=utf-8',
                    processData: false,
                    success: function (resp) {
                        if (resp.success) {
                            bootstrapQ.alert({msg: resp.message}, function () {
                                location.reload();
                            })
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 3000});
                        }
                    },
                    error: function (error) {
                        bootstrapQ.msg({msg: "网络异常 => " + error, type: 'danger', time: 3000});
                    }
                })
            }

            /* 图片上传 */
            // 模拟点击
            function thumbClick(dom) {
                let fileSelector = $('#fileSelector');
                fileSelector.click(); // 模拟点击 file 控件
                fileSelector[0].target = dom; // dom指向 <img>控件
            }

            // 图片清除
            function thumbDelete(dom) {
                let thumb = $(dom).prev('.thumb'); // 找兄弟 dom 元素
                $(thumb).prop('src', /*[[@{/img/imageup.png}]]*/'');
                $(thumb).data = null;
            }

            // 图片上传
            function selectFile(btn) {
                // 获取选择的文件
                let file = btn.files[0]; // 获取用户选择的文件
                let formData = new FormData(); // 构造表单对象
                formData.append('file', file); // 添加文件表单项

                btn.value = ''; // 清除文件选择按钮的选择
                let thumb = btn.target; // <img> 控件

                // 文件后缀和大小检查
                let type = file.type;
                if (type !== 'image/jpeg' && type !== 'image/png') {
                    bootstrapQ.msg({msg: '不支持的类型' + type, type: 'warning', time: 2000});
                    return;
                }
                if (file.size > 3000000) {
                    bootstrapQ.msg({msg: '图片太大,不得大于3MB!', type: 'warning', time: 2000});
                    return;
                }

                /* 文件上传 */
                $.ajax({
                    url: /*[[@{/admin/site/imgUpload.do}]]*/'',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (resp) {
                        if (resp.success) {
                            let data = resp.data;
                            $(thumb).prop('src', data.url);
                            thumb.data = data; // 记录应答数据
                        } else {
                            bootstrapQ.msg({msg: resp.message, type: 'warning', time: 2000});
                        }
                    },
                    error: function () {
                        bootstrapQ.msg({msg: '网络异常', type: 'danger', time: 2000});
                    }
                });
            }
        </script>
    </body>
</html>